Paul's JavaScript Examples    
 
Converting kilograms to pounds and vice versa

Convertor script to convert pounds to kilograms and kilograms to pounds. Just fill in one value and click on the Convert button. use the Clear button to clear the values. Note, negative values are not supported.

Example

Weights
Kilograms
Pounds
  

Usage

<INPUT TYPE="button" VALUE="Convert" onClick=computeWeightForm(this.form)>
<INPUT TYPE="button" VALUE="Clear" onClick=clearWeightForm(this.form)>

Source

<SCRIPT LANGUAGE="javascript">
<!--
function checkNumber(numStr, fieldName)
{
	msg = fieldName + " field has invalid data: " + numStr.value;
	str = numStr.value;
	for (var i=0; i < str.length; i++)
	{
		var ch = str.substring(i,i+1);
		if ( (ch < "0" || ch > "9") && ch != '.' )
		{
			alert(msg);
			return false;
		}
	}
	return true;
}

function computeWeightForm(weightform)
{
	// if both forms empty - error
	if ( (weightform.kilogram.value == null || 
            weightform.kilogram.value.length == 0) &&
           (weightform.pound.value == null ||
            weightform.pound.value.length == 0) )
	{
		alert("Both fields empty.");
		return;
	}

	// if both forms filled error
	if ( (weightform.kilogram.value != null &&
		weightform.kilogram.value.length > 0) &&
		(weightform.pound.value != null &&
		 weightform.pound.value.length > 0) )
	{
		alert("Error: both fields have data.");
		return;
	}

	// calculate kilograms
	if ( (weightform.kilogram.value == null ||
		weightform.kilogram.value.length == 0) &&
		(weightform.pound.value != null &&
		 weightform.pound.value.length > 0) )
      {
		if (checkNumber(weightform.pound,"Pounds"))
		{
			weightform.kilogram.value = (weightform.pound.value * 0.455);
		}

	}

	// calculate pounds
	if ( (weightform.kilogram.value != null &&
	      weightform.kilogram.value.length > 0) &&
		(weightform.pound.value == null ||
	    	 weightform.pound.value.length == 0) )
	{
		if (checkNumber(weightform.kilogram,"Kilograms"))
		{
			weightform.pound.value = (weightform.kilogram.value / 0.455);
		}		
	}
}

// used for weight conversion
function clearWeightForm(weightform)
{
	weightform.kilogram.value="";
	weightform.pound.value="";
}
// -->
</SCRIPT>